package com.atguigu.gmall.publisher.service.impl;

import com.atguigu.gmall.publisher.service.DauService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DauServiceImpl implements DauService {

    public static final String indexNamePrefix="gmall0722_dau_info_";

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Map<String, Object> getDauStats(String td) {
        log.debug("查询当前 日活 日期："+td);
        Map<String, Object> dauMap = new HashMap<>();
        Long dauTotal = getDauTotal(td);
        dauMap.put("dauTotal",dauTotal);
        Map<String, Long> dauHourTdMap = getDauHour(td);
        Map<String, Long> dauHourYdMap = getDauHour(dateAdd(td,-1));
        dauMap.put("dauTd",dauHourTdMap);
        dauMap.put("dauYd",dauHourYdMap);
        return dauMap;
    }

    //查询日活总数
    private   Long  getDauTotal(String date){
        String indexName=indexNamePrefix+date;
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(0); //优化查询性能

        SearchRequest searchRequest = new SearchRequest(indexName).source(searchSourceBuilder) ;
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            return searchResponse.getHits().getTotalHits().value; //提取结果
        }catch (ElasticsearchStatusException ese){
             if( ese.status()== RestStatus.NOT_FOUND){
                 log.warn("不存在该索引:"+ese.getIndex().getName());
                 return 0L;
             }else{
                 throw  new RuntimeException("es 查询失败");
             }
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("es 查询失败");
        }

    }

    public Map<String,Long>  getDauHour(String date){

        String indexName=indexNamePrefix+date;
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(0);

        //聚合
        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("groupby_hour").field("hr").size(24);
        searchSourceBuilder.aggregation(aggregationBuilder);

        SearchRequest searchRequest = new SearchRequest(indexName).source(searchSourceBuilder) ;

        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            ParsedStringTerms hourAgg = searchResponse.getAggregations().get("groupby_hour");
            List<? extends Terms.Bucket> buckets = hourAgg.getBuckets();
            Map<String ,Long> dauHourMap=new HashMap<>();
            for (Terms.Bucket bucket : buckets) {
                dauHourMap.put(bucket.getKeyAsString(),bucket.getDocCount());
            }
            return dauHourMap;
        }catch (ElasticsearchStatusException ese){
            if( ese.status()== RestStatus.NOT_FOUND){
                log.warn("不存在该索引:"+ese.getIndex().getName());
                return  new HashMap<>();
            }else{
                throw  new RuntimeException("es 查询失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("es 查询失败");
        }
    }

    private String  dateAdd(String date , int addDays){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dateDt = simpleDateFormat.parse(date);
            Date newDate = DateUtils.addDays(dateDt, addDays);
            return  simpleDateFormat.format(newDate);

        } catch (Exception e) {
            e.printStackTrace();
           throw  new RuntimeException("日期转换失败 ："+e.getLocalizedMessage());
        }


    }


}
